import {User} from "@/models/auth"
import { encryptPassword, storeToken } from "@/utils/auth"
import { request } from "./request"
type AuthProgress = { publicKey: string, authProgressUUID: string }

export async function getRSAPublicKey(): Promise<AuthProgress> {
	return (await request(`/api/auth/rsa_public_key`, "POST", undefined)).data
}

async function sendLoginRequest(authProgressUUID: string, userName: string, encryptedPassword: string): Promise<string> {
	try {
		const res = await request(`/api/auth/login`, "POST", {
			userName,
			authProgressUUID,
			encryptedPassword
		})
		console.log(res)
		if (res.statusCode == 200) {
			uni.showToast({
				title: 'Login succeeded!',
				duration: 2000,
				icon: "success"
			});
			return (res.data as any).jwtToken as string
		} else {
			uni.showToast({
				title: 'Login Failed',
				duration: 2000,
				icon: "error"
			});
			throw Error(`Login Failed with response ${res.data}`)
		}
	} catch (err) {
		uni.showToast({
			title: 'Login Failed',
			duration: 2000
		});
		console.error(err);
		throw (Error(`${err}`));
	}
}

export async function login(userName: string, password: string): Promise<null> {
	const { publicKey, authProgressUUID } = await getRSAPublicKey()
	const encryptedPassword = encryptPassword(password, publicKey)
	try {
		const jwtToken = await sendLoginRequest(authProgressUUID, userName, encryptedPassword)
		storeToken(jwtToken)
	} catch (err) {
		console.error(err)
	}
}

export async function wechatLogin(code: string): Promise<null> {
	const loginRet: { jwtToken: string, userInfo: User } = (await request("api/auth/wechat_login", "POST", { code }) as any).data
	console.log('stored token', loginRet)
	storeToken(loginRet.jwtToken)
}